package com.leetroll.app.controller;

import com.leetroll.api.service.CartService;
import com.leetroll.api.service.OrderService;
import com.leetroll.app.annotation.OperationLogger.OperationLogger;
import com.leetroll.app.config.WePayConfig;
import com.leetroll.app.service.WePayService;
import com.leetroll.app.utils.AppJwtTokenUtil;
import com.leetroll.common.bean.ApiResponse;
import com.leetroll.common.entity.Order;
import com.leetroll.common.enums.EModule;
import com.leetroll.common.vo.OrderDetailVO;
import com.leetroll.common.vo.OrderVO;
import com.yungouos.pay.util.PaySignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/pay")
@Api(value = "支付相关接口", tags = {"支付相关接口"})
@Slf4j
public class PayController {
    private final OrderService orderService;
    private final AppJwtTokenUtil jwtTokenUtil;
    private final CartService cartService;
    private final WePayService wePayService;

    @Autowired
    public PayController(OrderService orderService, AppJwtTokenUtil jwtTokenUtil, CartService cartService, WePayService wePayService) {
        this.orderService = orderService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.cartService = cartService;
        this.wePayService = wePayService;
    }


    @ApiOperation(value = "微信支付", notes = "微信支付")
    @PostMapping("/wepay")
    public ApiResponse<Map<String, String>> wepay(HttpServletRequest request, @RequestBody OrderVO orderVO) {
        Order order;
        if (orderVO.getOrder().getBatchCode() == null) {
            Long userId = jwtTokenUtil.getUserId(request);
            //生成订单
            order = orderService.addOrder(userId, orderVO.getDetails());

            //移除购物车item
            List<Long> itemIds = orderVO.getDetails().stream().map(OrderDetailVO::getItemId).collect(Collectors.toList());
            cartService.delByUserIdAndItemId(userId, itemIds);

        } else {
            //修改订单
            order = orderService.updateOrder(orderVO.getOrder());
        }

        //生成支付二维码
        String payQrCode = wePayService.nativePay(order);

        Map<String, String> result = new HashMap<>();
        result.put("payQrCode", payQrCode);
        result.put("batchCode", order.getBatchCode());
        return ApiResponse.OK(result);
    }

    @ApiOperation(value = "微信支付回调", notes = "微信支付回调")
    @PostMapping("/callback")
    public String callback(@RequestParam Map<String, String> data, HttpServletRequest request, HttpServletResponse response) throws Exception {
        boolean checked = PaySignUtil.checkNotifySign(request, WePayConfig.KEY);
        if (!checked || data.get("code").equals("0")) {
            return "fail";
        }

        String batchCode = data.get("outTradeNo"); //商户订单号
        String payCode = data.get("payNo"); //支付单号
        String payTime = data.get("time");

        orderService.paySuccess(batchCode, payCode, payTime);
        log.info("[pay callback] : {}", data);

        PrintWriter writer = response.getWriter();
        writer.print("SUCCESS");
        return null;
    }

    @ApiOperation(value = "订阅", notes = "订阅")
    @OperationLogger(modul = EModule.PAY,type = "USER_SUBSCRIBE",desc = "用户订阅VIP")
    @GetMapping("/subscribe/{vip}")
    public ApiResponse<?> subscribe(@PathVariable Integer vip) {
        return ApiResponse.OK();
    }
}
